import React, { useState, useEffect } from 'react';
import Table from '@knownsec/react-component/dist/Table';
import Input from '@knownsec/react-component/dist/Input';
import Icon from '@knownsec/react-component/dist/Icon';
import Message from '@knownsec/react-component/dist/Message';
import Helper from '../../components/Helper';
import CollectFrequency from '../../components/CollectFrequency';
import pathOr from 'ramda/es/pathOr';
import s from './style.module.css';
import cn from 'classnames';
import { cloneDeep } from 'lodash';
import {
	FREQUENCY_NUMBERS,
	FREQUENCY_UNIT_MAP,
} from '../../../common/constants';

function AviliableCreateJob({ taskType, jobList, jobIds, data, setData }) {
	const resD = JSON.parse(sessionStorage.resD);
	const [taskList, setTaskList] = React.useState(data);
	const [selectedRowKeys, setSelectedRowKeys] = useState([]);
	const jobMap = jobList.reduce((t, i) => {
		t[i.value] = i.label.split('\t')[1];
		return t;
	}, {});
	const changeItem = (newItem, index) => {
		const list = cloneDeep(taskList).map((item, k) => {
			if (k === index) return newItem;
			return item;
		});
		setTaskList(list);
	};
	const tableMethod = (type, index) => {
		if (jobIds.length === 0) {
			return Message.show({
				type: 'error',
				message: '请先选择资产地址',
			});
		}
		let list = cloneDeep(taskList);
		if (type === 'removeBatch') {
			list = list.reduce((t, i, k) => {
				if (selectedRowKeys.indexOf(k) === -1) {
					t.push(i);
				}
				return t;
			}, []);
			setSelectedRowKeys([]);
		} else {
			const addRow = addNewItem(taskList[index].jobId);
			addRow.name = '';
			addRow.target = '';
			if (type === 'add') {
				list.splice(index + 1, 0, addRow);
			} else {
				list.splice(index, 1);
			}
		}
		if (list.length === 0) {
			list.push(addNewItem());
		} else {
			list = list.map((i, k) => {
				i.key = k;
				return i;
			});
		}
		setTaskList(list);
	};
	const addNewItem = id => {
		let jobId = '';
		let jobName = '';
		if (id) {
			jobId = id;
			jobName = jobMap[id];
		}
		return {
			enableSitePortraitTriggerMonitor: false,
			enable: true,
			name: '',
			target: '',
			key: 0,
			jobId,
			jobName,
			interval: 300000,
			taskId: '',
		};
	};
	useEffect(() => {
		const list = cloneDeep(taskList);
		if (jobIds.length === 0) {
			const item = addNewItem();
			item.key = 0;
			setTaskList([item]);
		} else {
			const newItemList = jobIds.map((id, index) => {
				const item = addNewItem(id);
				item.target = '/';
				item.name = '首页';
				item.key = index;
				return item;
			});
			if (list.length === 1 && !list[0].jobId) {
				// 占位行
				setTaskList(newItemList);
			} else {
				const taskMap = taskList.reduce((t, i) => {
					if (t[i.jobId]) {
						t[i.jobId].push(i);
					} else {
						t[i.jobId] = [i];
					}
					return t;
				}, {});
				const resultList = jobIds.reduce((t, id, index) => {
					if (taskMap[id]) {
						t.push(...taskMap[id]);
					} else {
						const item = addNewItem(id);
						item.target = '/';
						item.name = '首页';
						item.key = index;
						t.push(item);
					}
					return t;
				}, []);
				setTaskList(resultList);
			}
		}
	}, [jobIds, taskType]);

	useEffect(() => {
		if (JSON.stringify(data) !== JSON.stringify(taskList)) {
			setData(taskList);
		}
	}, [taskList]);
	const columns = () => {
		const col = [
			{
				title: <div className={s.required}>任务名称</div>,
				key: 'name',
				dataIndex: 'name',
				width: 200,
				shouldCellUpdate: (pre, cur) => pre.name !== cur.name,
				render(e, row, index) {
					return (
						<Input
							value={e}
							disabled={jobIds.length === 0}
							onChange={({ value }) =>
								changeItem({ ...row, name: value }, index)
							}
						/>
					);
				},
			},
			{
				title: (
					<div className={cn(s.df, s.aic, s.required)}>
						监测目标
						<Helper overlay="如您需要监测地址入口是'https://www.scanv.com/admin/'，可在此输入'/admin/'即可；若您需要监测的地址是资产本身，则在此输入'/'即可。" />
					</div>
				),
				key: 'target',
				dataIndex: 'target',
				render(e, row, index) {
					return taskType === 'http' ? (
						<Input
							onChange={({ value }) =>
								changeItem({ ...row, target: value }, index)
							}
							prepend={
								row.jobName && <span title={row.jobName}>{row.jobName}</span>
							}
							className={s.preInput}
							disabled={jobIds.length === 0}
							placeholder={jobIds.length === 0 && '请先选择资产地址'}
							value={e}
						/>
					) : (
						<Input
							value={row.jobName}
							placeholder={jobIds.length === 0 && '请先选择资产地址'}
							disabled
						/>
					);
				},
			},
			{
				title: '监测频率',
				key: 'interval',
				dataIndex: 'interval',
				className: s.tou,
				width: taskType === 'http' ? 200 : 240,
				render(e, row, index) {
					return (
						<CollectFrequency
							value={e}
							onChange={value => changeItem({ ...row, interval: value }, index)}
							disabled={jobIds.length === 0}
							maxFreq={pathOr(0, ['balance', 'httpMaxFreq', 'total'], resD)}
							numbers={FREQUENCY_NUMBERS}
							unitMap={FREQUENCY_UNIT_MAP}
						/>
					);
				},
			},
			{
				title: (
					<div className={s.pl30}>
						<Icon
							type="remove"
							disabled={jobIds.length === 0}
							onClick={() => tableMethod('removeBatch')}
							className={cn(s.errorColor, s.fs20, s.methodIcon, {
								[s.show]: selectedRowKeys.length > 0,
							})}
						/>
					</div>
				),
				key: 'method',
				dataIndex: 'method',
				width: taskType === 'http' ? 80 : 40,
				render(e, row, index) {
					return (
						<div className={cn(s.df, s.aic)}>
							{taskType === 'http' && (
								<Icon
									type="add"
									onClick={() => tableMethod('add', index)}
									className={cn(s.cp, s.primaryColor, s.fs20, s.mr10)}
								/>
							)}
							<Icon
								type="remove"
								onClick={() => tableMethod('remove', index)}
								className={cn(s.cp, s.errorColor, s.fs20)}
							/>
						</div>
					);
				},
			},
		];
		return col;
	};
	return (
		<Table
			className={cn(s.w840, s.ml36, s.mb20)}
			key={Math.random().toString().slice(6)}
			rowSelection={{
				selectedRowKeys,
				columnWidth: 50,
				onChange: newSelectedRowKeys => {
					setSelectedRowKeys(newSelectedRowKeys);
				},
			}}
			columns={columns()}
			data={taskList}
			pro
		/>
	);
}
export default AviliableCreateJob;
